package com.rtx.wms.std.po.service.impl;

import java.util.List;import java.util.stream.Collector;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.wms.std.po.bean.ApiCarton;
import com.rtx.wms.std.po.bean.ApiPo;
import com.rtx.wms.std.po.bean.ApiPodetail;
import com.rtx.wms.std.po.mapper.ApiPoMapper;
import com.rtx.wms.std.po.service.ApiCartonService;
import com.rtx.wms.std.po.service.ApiPoService;
import com.rtx.wms.std.po.service.ApiPodetailService;

import cn.hutool.core.util.IdUtil;

@Service
public class ApiPoServiceImpl extends ServiceImpl<ApiPoMapper, ApiPo> implements ApiPoService{

	@Autowired
	ApiCartonService apiCartonService;
	
	@Autowired
	ApiPodetailService apiPodetailService;
	
	@Transactional
	@DataSourceAnnotation
	@Override
	public void insertApiPoAndpoDetailAndCartonid(String datasourckey, ApiPo apipo) {
		String batchid = IdUtil.getSnowflakeNextId()+"";
		for(ApiCarton carton:apipo.getCarton()) {
			if(StringUtils.hasLength(carton.getQty())) {
				carton.setBatchid(batchid);
				apiCartonService.save(carton);
			}
		}
		
		for(ApiPodetail podetail:apipo.getPodetail()) {
			podetail.setBatchid(batchid);
			List<ApiCarton> findtoid = apipo.getCarton().stream().filter(temp->podetail.getExternlineno().equals(podetail.getExternlineno())).collect(Collectors.toList());
			if(!CollectionUtils.isEmpty(findtoid)) {
				podetail.setToid(findtoid.get(0).getId());
			}
			podetail.setToid(batchid);
			apiPodetailService.insertApiPodetail(podetail);
		}
		
		apipo.setEdiflag("P");
		apipo.setBatchid(batchid);
		this.baseMapper.rtxconfigColumnsSave(apipo);
	}

	@DataSourceAnnotation
	@Override
	public List<ApiPo> querApipo(String datasourckey, Wrapper<ApiPo> qw) {
		List<ApiPo> list = baseMapper.selectList(qw);
		for(ApiPo apipo:list) {
			LambdaQueryWrapper<ApiPodetail> pdqw = Wrappers.lambdaQuery();
			pdqw.eq(ApiPodetail::getBatchid, apipo.getBatchid());
			List<ApiPodetail> pdlist = apiPodetailService.list(pdqw);
			apipo.setPodetail(pdlist);
			
			LambdaQueryWrapper<ApiCarton> acqw = Wrappers.lambdaQuery();
			acqw.eq(ApiCarton::getBatchid, apipo.getBatchid());
			List<ApiCarton> clist =	apiCartonService.list(acqw);
			apipo.setCarton(clist);
			
     	}
		
		return list;
	}

	@DataSourceAnnotation
	@Override
	public void updateByWrapper(String datasourckey, Wrapper<ApiPo> qw) {
		this.update(qw);
	}
	
	
	
}
